using System;
using System.Data;
using System.Data.SqlClient;
using System.Net.Mail;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Net.Configuration;

public partial class ListBooks : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (null != Membership.GetUser())
        {
            if (Roles.IsUserInRole(Membership.GetUser(true).UserName, "user"))
            {
                ((Label)this.LoginViewUser.FindControl("errorLabel")).Visible = false;
                ((DetailsView)this.LoginViewUser.FindControl("bookDetailsView")).Visible = false;
                ((Label)this.LoginViewUser.FindControl("detailsLabel")).Visible = false;
                ((Label)this.LoginViewUser.FindControl("detailsComplete")).Visible = false;
            }
        }
    }

    protected void bookListView_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName.Equals("Select"))
        {
            int index = Convert.ToInt32(e.CommandArgument); // Get the index of the clicked row
            showBookDetails(index);
        }
    }

    private void showBookDetails(int rowIndex)
    {
        DetailsView bookDetailsView = ((DetailsView)this.LoginViewUser.FindControl("bookDetailsView"));
        bookDetailsView.PageIndex = rowIndex;
        ((DetailsView)this.LoginViewUser.FindControl("bookDetailsView")).Visible = true;
        ((Label)this.LoginViewUser.FindControl("detailsLabel")).Visible = true;
    }

    protected void bookDetailsView_ItemCommand(object sender, DetailsViewCommandEventArgs e)
    {
        if (e.CommandName.Equals("Request"))
        {
            int index = Convert.ToInt32(e.CommandArgument); // Get the index of the clicked row
            RequestBook(index);
        }
    }

    private void RequestBook(int rowIndex)
    {
        GridView bookListView = ((GridView)this.LoginViewUser.FindControl("bookListView"));
        DetailsView bookDetailsView = ((DetailsView)this.LoginViewUser.FindControl("bookDetailsView"));

        if (int.Parse(bookDetailsView.Rows[5].Cells[1].Text) - int.Parse(bookDetailsView.Rows[6].Cells[1].Text) <= 0)
        {
            ((Label)this.LoginViewUser.FindControl("errorLabel")).Visible = true;
        }
        else
        {
            /* Grab bookid from the GridView */
            string primaryKey = (string)bookListView.DataKeys[rowIndex].Value;

            SqlConnection connection =
                new SqlConnection(ConfigurationManager.ConnectionStrings["sylib"].ConnectionString);
            connection.Open();

            /* Add 1 to the requested count */
            string sCommand = "UPDATE [books] SET [requested] = [requested]+1 WHERE [bookid] = '" + primaryKey + "'";
            SqlCommand cmd = new SqlCommand(sCommand, connection);
            cmd.ExecuteNonQuery();
            bookDetailsView.DataBind();

            /* Add username to the requests table */
            sCommand = "INSERT INTO requests(username,requestedbookid) VALUES('"+ User.Identity.Name +"','"+ 
                primaryKey +"')";
            cmd = new SqlCommand(sCommand, connection);
            cmd.ExecuteNonQuery();

            /* grab book and transaction information */
            sCommand = "SELECT [requestid], [title] FROM [requests], [books] WHERE [bookid] = '" + primaryKey +
                "' AND [requestedbookid] = '" + primaryKey + "' AND [username] = '" + User.Identity.Name + "'" ;
            cmd = new SqlCommand(sCommand, connection);
            SqlDataReader dataReader;
            dataReader = cmd.ExecuteReader();
            dataReader.Read();
            string transactionId = dataReader.GetInt32(0).ToString();
            string bookTitle = dataReader.GetString(1);

            connection.Close();

            /* Give the user their information on screen */
            ((Label)this.LoginViewUser.FindControl("detailsComplete")).Visible = true;
            ((Label)this.LoginViewUser.FindControl("detailsComplete")).Text = "Your request for the book <i>" +
                bookTitle + "</i> has been accepted, Request ID is " + transactionId + ".";
            ((Label)this.LoginViewUser.FindControl("detailsComplete")).Text += 
                "<br />A confirmation email will be sent " + Membership.GetUser().Email +
                " and an administrator shortly.";

            /* Send an email to the user with thier information */
            SmtpClient mailClient = new SmtpClient();
            mailClient.Send(((SmtpSection)ConfigurationManager.GetSection
                ("system.net/mailSettings/smtp")).From, Membership.GetUser().Email, "Sylib book request (" + 
                transactionId + ")", "You have requested the book [" + bookTitle + 
                "] through the Sylib service.  Your Request ID for this transaction is " + transactionId +
                ".  You can review this transaction by visiting the My Books section of the Sylib service.  " + 
                "This is an automatic message, replies will be sent directly to " + 
                ((SmtpSection)ConfigurationManager.GetSection("system.net/mailSettings/smtp")).From + 
                ".\n\nIf this has been a mistake, please just ignore this message.");

            /* If the admin has it set, send the admin a notification too */
            connection = new SqlConnection(ConfigurationManager.ConnectionStrings["sylibSettings"].ConnectionString);
            connection.Open();
            sCommand = "SELECT [sendAdminEmail] FROM [settings] WHERE [id] = 0";
            cmd = new SqlCommand(sCommand, connection);
            int sendAdminEmail = (int)cmd.ExecuteScalar();
            if (1 == sendAdminEmail)
                mailClient.Send(((SmtpSection)ConfigurationManager.GetSection("system.net/mailSettings/smtp")).From,
                    ((SmtpSection)ConfigurationManager.GetSection("system.net/mailSettings/smtp")).From, 
                    "Sylib book request (" + transactionId + ")", "User " + User.Identity.Name + 
                    " has requested the book [" + bookTitle + "] from you.  The Transaction ID is logged as " +
                    transactionId + ".");
            connection.Close();
        }
    }
}
